//
//  AddNewMes.m
//  testjson
//
//  Created by fcbayern on 2020/11/30.
//  Copyright © 2020 fcbayern. All rights reserved.
//

#import "AddNewMes.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "DLPhotoPicker.h"

@interface AddNewMes ()
@property(strong,nonatomic)UILabel * Title;
@property(strong,nonatomic)UILabel * Tag;
@property(strong,nonatomic)UILabel * details;
@property(strong,nonatomic)UITextField * entertitle;
@property(strong,nonatomic)UITextField * entertag;
@property(strong,nonatomic)UITextView * enterdetail;
@property(strong,nonatomic)UIButton * publish;
@property(strong,nonatomic)UILabel * setpublic;
@property(strong,nonatomic)UISwitch * ispublic;
@property(strong,nonatomic)UIScrollView * scroll;
@property (nonatomic,strong)UIButton * addpic;
@property(nonatomic,strong)UIImageView * originview;
@property(nonatomic,strong)NSMutableArray * arrforimage;
@property int check_publish;
@property int number_pic;
@property(strong,nonatomic)NSString * urltype;
@end

@implementation AddNewMes

- (void)viewDidLoad
{
    [super viewDidLoad];
    _check_publish = 0;
    _number_pic = 0;
    _arrforimage = [[NSMutableArray alloc]init];
    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.view.backgroundColor = [UIColor whiteColor];
    _scroll.backgroundColor = [UIColor whiteColor];
    _scroll.contentSize = CGSizeMake(self.view.frame.size.width, 2000);
    _scroll.delegate = self;
    [self.view addSubview:_scroll];
    
    
    _addpic = [[UIButton alloc]init];
    _Title = [[UILabel alloc] init];
    _details = [[UILabel alloc]init];
    _Tag = [[UILabel alloc]init];
    _entertitle = [[UITextField alloc]init];
    _enterdetail = [[UITextView alloc]init];
     _entertag = [[UITextField alloc]init];
    _publish = [[UIButton alloc]init];
    _ispublic = [[UISwitch alloc]init];
    _setpublic = [[UILabel alloc]init];
    _originview = [[UIImageView alloc] init];
    [_scroll addSubview:_addpic];
    [_scroll addSubview:_Title];
    [_scroll addSubview:_details];
    [_scroll addSubview:_Tag];
    [_scroll addSubview:_entertitle];
    [_scroll addSubview:_enterdetail];
    [_scroll addSubview:_entertag];
    [_scroll addSubview:_publish];
    [_scroll addSubview:_setpublic];
    [_scroll addSubview:_ispublic];
    [_scroll addSubview:_originview];
    
    _Title.text = @"标题:";
     _Title.font = [UIFont systemFontOfSize:25];
    _details.text = @"内容:";
     _details.font = [UIFont systemFontOfSize:25];
    _Tag.text = @"标签";
    _Tag.font = [UIFont systemFontOfSize:25];
    _setpublic.text = @"是否公开";
       _publish.backgroundColor = [UIColor whiteColor];
       _publish.layer.borderColor = [UIColor blackColor].CGColor;
       _publish.layer.borderWidth = 2;
       _publish.layer.cornerRadius = 15;
       [_publish setTitle:@"发布" forState:UIControlStateNormal];
        _publish.font = [UIFont systemFontOfSize:20];
       [_publish setTitleColor:[UIColor colorWithRed: 0/ 255.0 green:191 / 255.0 blue:255 / 255.0 alpha:1] forState:UIControlStateNormal];
    [_addpic setImage:[UIImage imageNamed:@"im"] forState:UIControlStateNormal];
    _entertitle.layer.borderWidth = 1.0f;
    _enterdetail.layer.borderWidth = 1.0f;
    _entertitle.layer.cornerRadius = 10;
    _enterdetail.layer.cornerRadius = 10;
    _entertag.layer.borderWidth = 1.0f;
    _entertag.layer.cornerRadius = 10;
    _enterdetail.font = [UIFont systemFontOfSize:15];
     _entertitle.font = [UIFont systemFontOfSize:15];
     _entertag.font = [UIFont systemFontOfSize:15];
    
    [_Title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_scroll.mas_left).with.offset(self.view.frame.size.width*0.05);
        make.top.equalTo(_scroll.mas_top).with.offset(self.view.frame.size.height*0.05);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.2);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.1);
        
    }];
    [_Tag mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_scroll.mas_left).with.offset(self.view.frame.size.width*0.05);
        make.top.equalTo(_Title.mas_bottom).with.offset(self.view.frame.size.height*0.03);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.2);
         make.height.equalTo(self.view.mas_width).multipliedBy(0.1);
    }];
    
    [_setpublic mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(_scroll.mas_left).with.offset(self.view.frame.size.width*0.05);
           make.top.equalTo(_enterdetail.mas_bottom).with.offset(self.view.frame.size.height*0.03);
           make.width.equalTo(self.view.mas_width).multipliedBy(0.2);
            make.height.equalTo(self.view.mas_width).multipliedBy(0.1);
       }];
    
    [_ispublic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_setpublic.mas_right).with.offset(self.view.frame.size.width*0.05);
        make.top.equalTo(_enterdetail.mas_bottom).with.offset(self.view.frame.size.height*0.03);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.2);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.1);
    }];
    
    [_details mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_scroll.mas_left).with.offset(self.view.frame.size.width*0.05);
        make.top.equalTo(_Tag.mas_bottom).with.offset(self.view.frame.size.height*0.03);
        make.width.equalTo(self.view.mas_width).multipliedBy(0.2);
         make.height.equalTo(self.view.mas_width).multipliedBy(0.1);
    }];
    [_entertag mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_Title.mas_right).with.offset(self.view.frame.size.width*0.05);
           make.top.equalTo(_Tag);
           make.width.equalTo(_Title).multipliedBy(3);
           make.height.equalTo(_Title);
       }];
       
       
       
    [_entertitle mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(_Title.mas_right).with.offset(self.view.frame.size.width*0.05);
              make.top.equalTo(_Title);
              make.width.equalTo(_Title).multipliedBy(3);
           make.height.equalTo(_Title);
          }];
    
    [_enterdetail mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_Title.mas_right).with.offset(self.view.frame.size.width*0.05);
           make.top.equalTo(_details);
           make.width.equalTo(_Title).multipliedBy(3);
           make.height.equalTo(_Title).multipliedBy(5);
       }];
    
    [_addpic mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).with.offset(-self.view.frame.size.width*0.06);
        make.top.equalTo(_enterdetail.mas_bottom).with.offset(self.view.frame.size.height*0.13);
           make.width.equalTo(self.view.mas_width).multipliedBy(0.4);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.2);
    }];
    [_addpic addTarget:self action:@selector(addpicture:) forControlEvents:UIControlEventTouchUpInside];
    
    [_originview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_addpic.mas_bottom).with.offset(self.view.frame.size.height*0.05*0.5);
        make.left.equalTo(self.view.mas_left).with.offset(self.view.frame.size.width*0.05);
         make.width.equalTo(self.view).multipliedBy(0.25);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.15);
    }];
    
    [_publish mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_scroll);
        make.top.equalTo(_originview.mas_bottom).with.offset(self.view.frame.size.height*0.5);
           make.width.equalTo(self.view.mas_width).multipliedBy(0.4);
        make.height.equalTo(self.view.mas_width).multipliedBy(0.2);
       }];
    
    [_publish addTarget:self action:@selector(Publish:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)Publish:(id)sender{
    if(_originview.image == nil){
        _urltype = @"text";
    }
    else{
        _urltype = @"album";
    }
    
    NSString * str_title = _entertitle.text;
    NSString * str_detail = _enterdetail.text;
    NSMutableArray * res_tag = [[NSMutableArray alloc]initWithObjects:_entertag.text, nil];
    int  checkpublic = _ispublic.on;
    BOOL check_is_public;
    if(checkpublic == 0){
        check_is_public = false;
    }
    else {
        check_is_public = true;
    }
    NSDictionary * parameters = @{
        @"title":str_title,
        @"detail":str_detail,
        @"tags":res_tag,
        @"isPublic":@(check_is_public)
    };
    NSDictionary * parameters_pic = @{
           @"title":str_title,
           @"detail":str_detail,
           @"tags":_entertag.text,
           @"isPublic":@(check_is_public)
       };
    NSString *url =[[NSString alloc]initWithFormat:@"%@%@",@"http://172.18.178.56/api/content/",_urltype];
    if([_urltype isEqualToString:@"text"]){
        AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * returnjson = (NSDictionary *)responseObject;
        NSString * State = returnjson[@"State"];
        if([State isEqualToString:@"success"]){
            UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"发布成功" preferredStyle:UIAlertControllerStyleAlert];
                   [self presentViewController:alert1 animated:YES completion:nil];
                   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                       [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                   });
        }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"123");
        }];
    }
    else{
        AFHTTPSessionManager * manager2 = [AFHTTPSessionManager manager];
        manager2.responseSerializer = [AFJSONResponseSerializer serializer];
        manager2.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager2 POST:url parameters:parameters_pic headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
               
            for(int i = 0;i<_arrforimage.count;++i){
                NSData * temp = [self->_arrforimage objectAtIndex:i];
                NSString * name =[[NSString alloc]initWithFormat:@"%@%d",@"file",i];
                NSString * thumb =[[NSString alloc]initWithFormat:@"%@%d",@"thumb",i];
                [formData appendPartWithFileData:temp name:name fileName:name mimeType:@"image/jpg"];
                [formData appendPartWithFileData:temp name:thumb fileName:thumb mimeType:@"image/jpg"];
            }
                

           } progress:^(NSProgress * _Nonnull uploadProgress) {
               
           } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               NSLog(@"%@",responseObject);
           } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               NSLog(@"%@",error);
           }];
    }
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)addpicture:(id)sender{
    DLPhotoPickerViewController *picker = [[DLPhotoPickerViewController alloc] init];
    picker.delegate = self;
    picker.pickerType = DLPhotoPickerTypePicker;
    picker.navigationTitle = NSLocalizedString(@"相册", nil);
    
    [self presentViewController:picker animated:YES completion:nil];
}





#pragma mark DLPhotoPickerViewControllerDelegate

// cancel
- (void)pickerControllerDidCancel:(DLPhotoPickerViewController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// picked
-(void)pickerController:(DLPhotoPickerViewController *)picker didFinishPickingAssets:(NSArray *)assets
{
    UIImageView * newview;
    ++_number_pic;
    if(_number_pic != 1){
        newview = [[UIImageView alloc]init];
        [_scroll addSubview:newview];
        [newview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_addpic.mas_bottom).with.offset(self.view.frame.size.height*0.05*0.5+ _originview.frame.size.height*((_number_pic-1)/3)*1.2);
            make.left.equalTo(_originview.mas_left).with.offset(self.view.frame.size.width*0.30*((_number_pic-1)%3));
            make.width.equalTo(self.view).multipliedBy(0.25);
            make.height.equalTo(self.view.mas_width).multipliedBy(0.15);
        }];
       
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    self.assets = [NSArray arrayWithArray:assets];
    //show the first image:
    DLPhotoAsset *asset = [self.assets objectAtIndex:0];
    CGSize targetSize = CGSizeMake(100, 100);
    [asset requestThumbnailImageWithSize:targetSize completion:^(UIImage *image, NSDictionary *info) {
        NSData * fileData;
        if(self->_number_pic == 1){
            self->_originview.image = image;
            fileData = UIImageJPEGRepresentation(image, 0.4);
        }
        else{
            newview.image = image;
           fileData = UIImageJPEGRepresentation(image, 0.4);
        }
        [self->_arrforimage addObject:fileData];
        NSLog(@"%d",self->_arrforimage.count);
    }];
        
    
}




@end
